package com.sunchangming.stmdb.xgen;

import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class StmdbConverter implements Converter {

	@SuppressWarnings("rawtypes")
	@Override
	public boolean canConvert(Class clazz) {
		return clazz.equals(StmdbConfig.class);
	}

	@Override
	public void marshal(Object arg0, HierarchicalStreamWriter arg1, MarshallingContext arg2) {

	}

	@Override
	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
		final StmdbConfig ns = new StmdbConfig();
		final String serverid = reader.getAttribute("serverid");
		if (serverid == null)
			throw new ConversionException("stmdb节点必须具有serverid属性");
		ns.serverid = Integer.valueOf(serverid);

		while (reader.hasMoreChildren()) {
			reader.moveDown();
			try {
				if ("bean".equals(reader.getNodeName())) {
					final Bean b = (Bean) context.convertAnother(ns, Bean.class);
					b.parent = ns;
					ns.beans.add(b);
				} else if ("enum".equals(reader.getNodeName())) {
					final Enum b = (Enum) context.convertAnother(ns, Enum.class);
					b.parent = ns;
					ns.enums.add(b);
				} else if ("table".equals(reader.getNodeName())) {
					final Table b = (Table) context.convertAnother(ns, Table.class);
					b.parent = ns;
					ns.tables.add(b);
				} else
					throw new ConversionException("不认识的节点" + reader.getNodeName());
			} finally {
				reader.moveUp();
			}
		}
		return ns;
	}

}
